#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

#define NUM_PROCESSES 50  // 创建的子进程数

pid_t pids[NUM_PROCESSES];  // 用于存储所有子进程的PID
pid_t canwrite_pid = -1;    // 用于存储执行 CanWrite 的子进程PID

// 清理函数：在父进程退出时杀死所有子进程
void cleanup_children(void) {
    for (int i = 0; i < NUM_PROCESSES; i++) {
        if (pids[i] > 0) {
            // 发送 SIGKILL 信号终止子进程
            kill(pids[i], SIGKILL);
        }
    }
    // 终止执行 ./CanWrite 的进程
    if (canwrite_pid > 0) {
        kill(canwrite_pid, SIGKILL);
    }
    printf("All child processes have been killed.\n");
}

int main() {
    int i;
    pid_t pid;

    // 注册清理函数
    atexit(cleanup_children);

    // 执行 ./CanWrite
    canwrite_pid = fork();
    if (canwrite_pid < 0) {
        perror("fork for CanWrite failed");
        exit(EXIT_FAILURE);
    }
    if (canwrite_pid == 0) {
        printf("Starting CanWrite (Process ID: %d)\n", getpid());
        execl("./CanWrite", "./CanWrite", (char *)NULL);  // 执行 ./CanWrite 命令
        perror("execl failed for CanWrite");  // 如果 execl 返回，表示出错
        exit(EXIT_FAILURE);
    }

    // 创建 NUM_PROCESSES 个 TcpClient 子进程
    for (i = 0; i < NUM_PROCESSES; i++) {
        pid = fork();  // 创建子进程

        if (pid < 0) {
            // fork 失败
            perror("fork failed");
            exit(EXIT_FAILURE);
        }

        if (pid == 0) {
            // 子进程
            printf("Starting TcpClient with port 8082 (Process ID: %d)\n", getpid());
            execl("./TcpClient", "./TcpClient", "8082", (char *)NULL);  // 执行 ./TcpClient 8082 命令
            perror("execl failed for TcpClient");  // 如果 execl 返回，表示出错
            exit(EXIT_FAILURE);
        }

        // 父进程保存子进程的 PID
        pids[i] = pid;
    }

    // 父进程等待所有子进程完成
    for (i = 0; i < NUM_PROCESSES; i++) {
        wait(NULL);
    }
    // 父进程等待 ./CanWrite 进程完成
    waitpid(canwrite_pid, NULL, 0);

    printf("All TcpClient and CanWrite processes have completed.\n");
    return 0;
}
